package com.wt.springsamples.tx;

import com.wt.springsamples.common.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 本地事务失效时：原理，调用自身方法时，被调用的方法没有通过代理对象调用，导致Aop失效，
 * 解决办法：
 *  1、引入spring-boot-starter-aop包
 *  2、开启Aspectj代理功能，@EnableAspectJAutoProxy(exposeProxy = true)
 *  3、方法内部使用代理对象调用本类方法
 *    TxService txService = (TxService) AopContext.currentProxy();
 *
 */
@Service
public class UserService {

    public UserService() {
        System.out.println("UserService init");
    }

    @Autowired
    private TxDao txDao;

    @Transactional
    public  void test(){
        txDao.add();
    }

    @Transactional(propagation= Propagation.REQUIRED,timeout = 2)
    public  void save(){
        System.out.println(" UserService save called ");
    }

    @Transactional(propagation= Propagation.REQUIRES_NEW,timeout = 2)
    public  void requiresNew(){
        System.out.println(" UserService requiresNew called ");
        throw  new BizException("异常");
    }

    @Transactional(propagation= Propagation.NESTED)
    public  void update(){
//
        System.out.println(" UserService update called ");
        throw  new BizException("异常");
    }

    @Transactional(propagation= Propagation.REQUIRED,timeout = 2)
    public  void delete(){
        System.out.println(" UserService delete called ");
    }

    @Transactional(propagation= Propagation.NEVER)
    public UserModel get(Integer id){
        System.out.println(" UserService get called ");
        return new UserModel();
    }


    @Transactional(propagation= Propagation.MANDATORY)
    public void config(){
        System.out.println(" UserService config called ");
    }

}
